package thread;

import java.util.PriorityQueue;
import java.util.TimerTask;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_DaChiZi
 * Date: 2025/6/23
 * Time: 20:47
 * 实现闹钟方法！！！！！
 */
class MyTimerTask implements Comparable<MyTimerTask>{
    public Runnable runnable;
    public long time;

    public MyTimerTask (Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }
    public void run () {
        runnable.run();
    }
    public long getTime () {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
}
class MyTimer {
    PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    public Object locker = new Object();

    public MyTimer() {
        Thread t = new Thread(() -> {
            while (true) {
                synchronized (locker) {
                    if (queue.isEmpty()) {
                        continue;
                    }
                    MyTimerTask current = queue.peek();
                    if (System.currentTimeMillis() >= current.getTime()) {
                        current.run();
                        queue.poll();
                    } else {
                        continue;
                    }
                }
            }
        });
        t.start();
    }

    public void schedule (Runnable runnable, long delay) {
        synchronized (locker) {
            MyTimerTask myTimerTask = new MyTimerTask(runnable,delay);
            queue.offer(myTimerTask);
        }
    }
}

public class Demo33 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(() -> {
            System.out.println("Hello1");
        },1000);
        myTimer.schedule(() -> {
            System.out.println("Hello2");
        },2000);
        myTimer.schedule(() -> {
            System.out.println("Hello3");
        },3000);
    }
}
